<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/7 0007
 * Time: 上午 8:35
 */
namespace Home\Controller;

use Think\Controller;

class AccountController extends SignInAgenController
{
    /*进入银行卡*/
    public function bankcard()
    {
        $sourceId = I('post.uid');
        if(empty($sourceId)){
            $sourceId = parent::getagenAccountId();
        }
        /*查询所有银行卡*/
        $bank = M("dropdown")->where(array("module" => "bankCode"))->field("code,val") -> select();
        /*所有的银行卡信息*/
        $cardlist = M("bank")
            ->where(array("bank.sourceId" => $sourceId, "bank.isDelete" => 2))
            ->order("bank.isDefault")
            ->select();
        return $this->ajaxSuccess(array("bank" => $bank, "cardlist" => $cardlist));
    }

    public function selectcard(){
        $id = I("post.id");
        $sourceId = I('post.uid');
        if(empty($sourceId)){
            $sourceId = parent::getagenAccountId();
        }
        $update = M("bank")->where(array("id" => $id,"sourceId"=>$sourceId))->find();
        $bank = M("dropdown")->where(array("module" => "bankCode"))->field("code,val")->select();
        return $this->ajaxSuccess(array("update"=>$update,"bank" => $bank));
    }

    public function savebank(){
        $id = I("post.id");
        $sourceId = I('post.uid');
        if(empty($sourceId)){
            $sourceId = parent::getagenAccountId();
        }
        /*查询所有银行卡*/
        $bank = M("dropdown")->where(array("module" => "bankCode"))->field("code,val")->select();
        $number = I("post.number");
        if (!isBankCard($number)) {
            return $this->ajaxError("该银行卡号无效！");
        }
        $data["sourceId"] = $sourceId;
        $data["name"] = I("name");
        $data["code"] = I("code");
        $data["branch"] = I("branch");
        $data["number"] = $number;
        $data["bankName"] = I("bankname");
        $data['updateTime'] = date("Y-m-d H:i:s");
        $dft = I("default");
        /*判断是否默认*/
        if($dft == "false"){
            $data["isDefault"] = 2;
        }
        else{
            $data["isDefault"] = 1;
            /*如果是默认把所有设为不默认*/
            $where2["sourceId"] = $sourceId;
            M("bank")->where($where2)->save(array("isDefault" => 2));
        }

        $res = M("bank")->where(array('id'=>$id))->save($data);
        if ($res) {
            return $this->ajaxSuccess("修改成功！");
        } else {
            return $this->ajaxError("修改失败！");
        }

    }

    /*添加银行卡*/
    public function addbank()
    {
        if (IS_POST) {
            $agenid = I('post.uid');
            if(empty($agenid)){
                $agenid = parent::getagenAccountId();
            }
            $name = I("post.name");
            $code = I("post.code");
            $barnch = I("post.branch");
            $number = I("post.number");
            if(empty($name) || empty($code) || empty($barnch) || empty($number)){
                return $this->ajaxError("相关信息未填写！");
            }
            if (!isBankCard($number)) {
                return $this->ajaxError("该银行卡号无效！");
            }
            $where['sourceId'] = $agenid;
            $where['number'] = $number;
            $where["isDelete"] = 2;
            $r = M("bank")->where($where)->select();//查询银行卡是否已经添加
            if ($r) {
                return $this->ajaxError("此银行卡已经存在");
            } else {
                $data["sourceId"] = $agenid;
                $data["name"] = I("name");
                $data["code"] = I("code");
                $data["branch"] = I("branch");
                $data["number"] = I("number");
                $data["bankName"] = I("bankname");
                $data['createTime'] = date("Y-m-d H:i:s");
                /*判断是否默认*/
                $dft = I("default");
                if($dft == "false"){
                    $data["isDefault"] = 2;
                } else {
                    $data["isDefault"] = 1;
                    $where2["sourceId"] = $agenid;
                    M("bank")->where($where2)->save(array("isDefault" => 2));
                }

                $res = M("bank")->add($data);
                if ($res) {
                    return $this->ajaxSuccess("添加成功！");
                } else {
                    return $this->ajaxError("添加失败！");
                }
            }
        }
    }

    /*设为默认银行卡*/
    public function setDefault()
    {
        $agenid = I('post.uid');
        if(empty($agenid)){
            $agenid = parent::getagenAccountId();
        }
        $id = I("post.id");
        $data["isDefault"] = 1;
        $data1["isDefault"] = 2;
        $where["id"] = array("neq", $id);
        $where["sourceId"] = $agenid;
        $res = M("bank")->where(array("id" => $id))->save($data);//将此银行卡设为默认
        M("bank")->where($where)->save($data1);//将本人其他银行卡取消默认
        if ($res) {
            return $this->ajaxSuccess("该银行卡已设为默认！");
        } else {
            return $this->ajaxError("操作失败！");
        }
    }

    /*删除银行卡*/
    public function remove()
    {
        $agenid = I('post.uid');
        if(empty($agenid)){
            $agenid = parent::getagenAccountId();
        }
        $id = I("post.id");
        $data["isDelete"] = 1;
        $res = M("bank")->where(array("id" => $id,"sourceId"=>$agenid))->save($data);
        if ($res) {
            $this->ajaxSuccess("操作成功");
        } else {
            $this->ajaxError("操作失败");
        }
    }


    //进入提现
    public function cash()
    {
        //用户ID
        $agenid = I('post.uid');
        if(empty($agenid)){
            $agenid = parent::getagenAccountId();
        }

        //查询是否绑定银行卡
        $cardCount = M("bank")
            ->where(array(
                "sourceId" => $agenid,
                "isDelete" => 2
            ))
            ->count();

        if (!$cardCount) {
            return $this->ajaxError("尚未绑定银行卡，请添加银行卡后重试！");
        }

//        $member = M("agen")->lock(true)->where(array("id"=>$agenid))->find();
        $bank_where["sourceId"] = $agenid;
        $bank_where["isDelete"] = 2;
        $recharge = M("agen")->where(array("id"=>$agenid))->find();//用户的信息
        /*查询用户的所有的银行卡*/
        $user_bank = M("bank")->where($bank_where)->order("isDefault asc")->find();
        $user_all_bank = M("bank")->where($bank_where)->select();
        return $this->ajaxSuccess(array("user_bank" => $user_bank,"user_all_bank"=>$user_all_bank ,"recharge" => $recharge));

    }


    //处理提取
    public function withdrawal()
    {
        if (IS_POST) {
            $id = I('post.uid');
            if(empty($id)){
                $id = parent::getagenAccountId();
            }
            $member = M("agen")->lock(true)->where(array('id' => $id))->find();
            $mobileCode = I("post.mobilecode");

            if (time() - parent::get("codetime") > 60) {
                parent::set("code",null);
            };
            if ($mobileCode != parent::get("code") || parent::get("code") == null) {
                return $this->ajaxError("验证码错误");
            }
            if ($member ['balance'] < 100) {
                return $this->ajaxError("余额不足100，不能提取！");
            } else {
                $amount = I("post.amount");
                $bankid = I("post.bankinfo");
                $bank_where["bank.id"] = $bankid;
                /*取得用户选择的银行卡信息*/
                $bankinfo = M("bank")->where($bank_where)->find();
                $account = $bankinfo["number"];

                /*添加提取表的内容*/
                $sn = date('YmdH') . substr(mt_rand(1000000, 999999999), 0, 4) . substr(mt_rand(1000000, 999999999), 0, 6);//生成订单号
                $adddata["agenId"] = $member['id'];
                $adddata["createTime"] = Z_TIME_STR;
                $adddata["updateTime"] = Z_TIME_STR;
                $adddata["branch"] = $bankinfo['branch'];
                $adddata["number"] = $account;
                $adddata["name"] = $member["name"];
                $adddata["amount"] = $amount;
                $adddata["status"] = 1;
                $adddata["cash"] = $amount;
                $adddata["bankName"] = $bankinfo['bankname'];

                $systemconfig = getConfig('deal');
                $shouxufei = $systemconfig['factorage']; //提现手续费
                $adddata["cash"] = $amount * (1 - $shouxufei);

                $adddata["amount"] = $amount;
                $adddata["status"] = "1";
                if ($amount < 100) {
                    return $this->ajaxError("最小提现金额为100！");
                }
                if ($member ['balance'] < $amount) {
                    return $this->ajaxError("余额不足！");
                }
                //开启事务
                $user = M();
                $user->startTrans();
                $addwithdrawal = M("withdrawal")->add($adddata);
                if (!$addwithdrawal) {
                    $user->rollback();
                    return $this->ajaxError("提取失败");
                }

                // 会员推荐减少
                $fields = array("balance" => array("exp", "balance-" . $amount));
                $where["id"] = $member['id'];
                $upemmber = M("agen")
                    ->where($where)
                    ->save($fields);

                if (!$upemmber) {
                    $user->rollback();
                    return $this->ajaxError("会员余额更改错误");
                }

                /*插入现金流量表*/
                $data['accountId'] = $member['id'];
                $data['accountType'] = '2';
                $data['sourceId'] = $addwithdrawal;
                $data['sourceType'] = '3';
                $data['type'] = '2';
                $data['moneyType'] = '2';
                $data['beforeMoney'] = $member['balance'];
                $data['changeMoney'] = $amount;
                $data['afterMoney'] = $member['balance'] - $amount;
                $data['createTime'] = date("Y-m-d H:i:s");
                $data['info'] = "提现";

                $addmoneylog = M("moneylog")->add($data);

                if ($addmoneylog) {
                    $user->commit();
                    parent::set("code","");
                    return $this->ajaxSuccess("申请提现成功！");
                } else {
                    $user->rollback();
                    return $this->ajaxError("申请提现失败！");
                }
            }
        }
    }


    /*短信*/
    public function getnum()
    {
        // 获取配置
        $sms = getConfig('sms');
        $url = $sms['url'];
        $key = $sms['key'];
        $tplId = $sms['tplId'];

        $code = rand(100000, 999999);
        parent::set("code", $code);
        parent::set("codetime", time());
        $sendUrl = $url; //短信接口的URL
        $agenid = $this->getagenAccountId();
        $agen = M('agen')->where(array('id'=>$agenid))->find();
        if(empty($agen['phone'])){
            return $this -> ajaxError("电话号码不存在！");
        }
        $smsConf = array(
            'key' => $key, //您申请的APPKEY
            'mobile' => $agen['phone'], //接受短信的用户手机号码
            'tpl_id' => $tplId, //您申请的短信模板ID，根据实际情况修改
            'tpl_value' => '#code#=' . $code . '&#company#=心体荟' //您设置的模板变量，根据实际情况修改
        );
        /*$res = M("agen")
            ->where(array("phone"=>$smsConf['mobile']))
            ->find();
        if(!$res){
            return $this -> ajaxError("电话号码不存在！");
        }*/

        $content = juhecurl($sendUrl, $smsConf, 1); //请求发送短信

        if ($content) {
            $result = json_decode($content, true);
            $error_code = $result['error_code'];
            if ($error_code == 0) {
                //状态为0，说明短信发送成功
                //echo "短信发送成功,短信ID：".$result['result']['sid'];
                return $this ->ajaxSuccess("发送成功！");
            } else {
                //状态非0，说明失败
                return $this ->ajaxError("发送失败！");
            }
        } else {
            //返回内容异常，以下可根据业务逻辑自行修改
            return $this ->ajaxError("发送失败！");
        }
    }


    /*提现记录*/
    public function record(){
        $id = I('post.uid');
        if(empty($id)){
            $id = parent::getagenAccountId();
        }
        $page=I('post.page');
        $list=20;
        $data = M('withdrawal')
            ->alias("w")
            ->join("LEFT JOIN agen ON w.agenId=agen.id")
            ->where(array("agenId"=>$id))
            ->field("w.*,agen.account,CASE w.`status` WHEN 1 THEN \"待审核\" WHEN 2 THEN \"已完成\" WHEN 3 THEN \"已驳回\" ELSE \"未知\" END stname")
            ->order("w.createTime desc")
            ->limit($page*$list,$list)
            ->select();
        return $this->ajaxSuccess($data);

    }

}